<template>
  <el-header class="header">
    <div id="header1">
      <el-header class="header-inner">
        <!-- 左侧 Logo 区 -->
        <div class="header-logo">
          <img src="@/assets/images/systemManagement/菜单.png" alt="菜单图标" />
          <span class="header-title">权限管理</span>
        </div>
        <!-- 右侧用户信息区 -->
        <div class="user-info">
          <img :src="userAvatar" alt="用户头像" class="user-avatar" />
          <span class="user-phone">{{ userName }}</span>
        </div>
      </el-header>
    </div>
  </el-header>
  <el-main class="main-container">
    <!-- 顶部操作栏 -->
    <div class="page-header">
      <div class="operation-buttons">
        <el-button type="danger" @click="openAddDialog">
          <el-icon>
            <Plus />
          </el-icon> 添加
        </el-button>
        <el-button @click="handleRefresh" type="info">
          <el-icon>
            <Refresh />
          </el-icon> 刷新
        </el-button>
      </div>
    </div>
    <!-- 树形权限表格 -->
    <el-table :data="tableData" border :loading="tableLoading"
      :tree-props="{ children: 'childList', hasChildren: 'hasChildren' }" style="width: 100%" row-key="id">
      <el-table-column prop="title" label="title" width="180" />
      <el-table-column prop="name" label="name" width="120" />
      <el-table-column prop="path" label="path" width="150" />
      <el-table-column label="is_left" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.isLeft == '1' ? 'success' : 'danger'">
            <span v-if="scope.row.isLeft == 1">是</span>
            <span v-if="scope.row.isLeft != 1">否</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="icon" width="60">
        <template #default="scope">
          <component :is="getIcon(scope.row.icon)" class="menu-icon" />
        </template>
      </el-table-column>
      <el-table-column prop="orders" label="sort" width="80" />
      <el-table-column label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.visible == '1' ? 'success' : 'danger'">
            <span v-if="scope.row.visible == '1'">启用</span>
            <span v-if="scope.row.visible == '0'">禁用</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button type="primary" size="small" @click="openEditDialog(scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加/编辑 -->
    <el-dialog v-model="dialogVisible" :title="editRow ? '编辑' : '添加'">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="上一级菜单">
          <el-select v-model="formData.parentId" placeholder="请选择父级">
            <el-option label="无" :value="0" />
            <el-option v-for="item in getParentOptions" :key="item.id" :label="item.title" :value="item.id">
              <!-- {{ item.title }} -->
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="title">
          <el-input v-model="formData.title" placeholder="请输入菜单标题" />
        </el-form-item>
        <el-form-item label="name">
          <el-input v-model="formData.name" placeholder="请输入唯一标识" />
        </el-form-item>
        <el-form-item label="path">
          <el-input v-model="formData.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="is_left">
          <el-radio v-model="formData.isLeft" :label="1">是</el-radio>
          <el-radio v-model="formData.isLeft" :label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="icon">
          <el-input v-model="formData.icon" placeholder="请输入图标名称（如HomeFilled）" />
        </el-form-item>
        <el-form-item label="sort">
          <el-input v-model.number="formData.orders" placeholder="请输入排序值" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="formData.visible" :label="'1'">启用</el-radio>
          <el-radio v-model="formData.visible" :label="'0'">禁用</el-radio>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </el-main>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { Plus, Refresh, HomeFilled, WarningFilled, Menu, UserFilled, Platform, WarnTriangleFilled, Grid, Briefcase, Shop, WalletFilled, StarFilled, Tools, Management, InfoFilled } from "@element-plus/icons-vue";
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElRadio, ElButton, ElDialog, ElTable, ElTableColumn, ElTag, ElIcon, ElMessage } from 'element-plus';
import { getMenuList, InsertMenu, getReturnmenu, getUpdateMenu } from "@/components/api/PermissionMange";

// 基础状态
const dialogVisible = ref(false);
const editRow = ref(null); // 编辑的行数据（添加时为null）
const menuListAll = ref(null);
// 表单数据
const formData = reactive({
  parentId: '', // 父级菜单name
  title: '',
  name: '',
  path: '',
  isLeft: 0, // 是/否
  icon: '',
  orders: null,
  visible: 0 // 启用/禁用
});

// 用户信息
const userAvatar = ref();
const userName = ref("15210418591");

// 表格加载状态
const tableLoading = ref(false);
// 表格数据源（树形结构，响应式数组）
const tableData = ref([]);
// 图标映射
const iconMap = {
  HomeFilled, Menu, UserFilled, WarningFilled, Platform, WarnTriangleFilled, Grid, Briefcase, Shop, WalletFilled, StarFilled, Tools, Management, InfoFilled
};


const getIcon = (iconName) => {
  return iconMap[iconName] || InfoFilled;
};

// 冒泡
function bubbleSort(arr) {
  const newArr = [...arr];
  for (let i = 0; i < newArr.length - 1; i++) {
    if (newArr[i].childList.length > 0) {
      bubbleSort(newArr[i].childList);
    }
    for (let j = 0; j < newArr.length - 1 - i; j++) {
      if (newArr[j].orders < newArr[j + 1].orders) {
        [newArr[j], newArr[j + 1]] = [newArr[j + 1], newArr[j]];
      }
    }
  }
  return newArr;
}


/* 加载菜单列表*/
const loadMenuList = () => {
  tableLoading.value = true;
  getMenuList({ token: sessionStorage.getItem("token") })
    .then(res => {
      if (res.code === 200) {
        // 关键处理：给每个节点添加hasChildren字段
        const formattedData = res.dataset.map(node => ({
          ...node,
          // 当childList存在且不为空时，hasChildren为true，否则为false
          hasChildren: Array.isArray(node.childList) && node.childList.length > 0
        }));
        // console.log(formattedData,"--------------");
        //  console.log(bubbleSort(formattedData));

        tableData.value = bubbleSort(formattedData); // 赋值处理后的数据

      } else {
        ElMessage.error(res.message || "获取菜单列表失败");
      }
    })
    .catch(err => {
      console.error("获取菜单列表失败：", err);
      ElMessage.error("获取菜单列表失败，请稍后再试");
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

// 组件挂载后自动加载数据
onMounted(() => {
  loadMenuList();
});


/**
 * 计算属性：可选择的父级菜单
 */
const getParentOptions = computed(() => {
  // const excludeName = editRow.value?.name; // 编辑时排除自身
  const flattenMenu = (menuList) => {
    return menuList.reduce((acc, item) => {
      // if (item.name !== excludeName) { // 排除自身
      acc.push(item);
      if (item.childrenList && item.childrenList.length) {
        acc.push(...flattenMenu(item.childrenList)); // 递归展开子菜单
      }
      // }
      return acc;
    }, []);
  };
  return flattenMenu(tableData.value); // 基于响应式数据tableData.value
});

/*添加*/
const openAddDialog = () => {
  editRow.value = null;
  // 重置表单所有字段
  formData.parentId = '';
  formData.title = '';
  formData.name = '';
  formData.path = '';
  formData.isLeft = '';
  formData.icon = '';
  formData.orders = null;
  formData.visible = '';
  dialogVisible.value = true;
};

/* 编辑 */
const openEditDialog = (row) => {
  console.log(row, '-------');
  editRow.value = row;
  formData.parentId = row.parentId;
  console.log(formData.parentId);

  // 回显其他字段
  formData.title = row.title;
  formData.name = row.name;
  formData.path = row.path;
  formData.isLeft = row.isLeft;
  formData.icon = row.icon;
  formData.orders = row.orders;
  formData.visible = row.visible;
  formData.id = row.id
  dialogVisible.value = true;
};

/**
 * 表单提交（添加/编辑）
 */
const handleConfirm = () => {
  if (editRow.value) {
    // 编辑：直接更新原行数据
    console.log(formData, "=================");
    const mydata = {
      parentId: formData.parentId, // 父级菜单name
      title: formData.title,
      name: formData.name,
      path: formData.path,
      isLeft: formData.isLeft, // 是/否
      icon: formData.icon,
      orders: formData.orders,
      visible: formData.visible,
      id: formData.id // 启用/禁用
    }
    console.log(mydata, "----------------------");

    getUpdateMenu(mydata)
      .then(res => {
        if (res.code === 200) {
          console.log(res);
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
        }
      })
  } else {
    const newItem = { ...formData };
    console.log(newItem);
    InsertMenu(newItem)
      .then(res => {
        console.log(res);
        if (res.code === 200) {
          console.log(res);
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
        }
      })
  }
  dialogVisible.value = false; // 关闭对话框
  // setTimeout(function(){
  //   loadMenuList()
  //   location.reload()
  // },400);

};

/**
 * 刷新按钮（重新加载数据）
 */
const handleRefresh = () => {
  loadMenuList(); // 重新请求菜单列表
};
</script>
<style lang="less" scoped>
/* 顶部导航栏 */
.header {
  height: 80px;
  background: #fff;
  border-bottom: 1px solid #e5e7eb;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .header-inner {
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
  }

  .header-logo {
    display: flex;
    align-items: center;
    gap: 10px;

    img {
      width: 24px;
      height: 24px;
    }

    .header-title {
      font-size: 18px;
      font-weight: 700;
      color: #333;
    }
  }

  :deep(.el-input) {
    box-sizing: border-box;
    width: 150px;
  }

  .el-select__wrapper {
    width: 150px;
  }

  .el-form-item__content {
    width: 180px;
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 10px;

    .user-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
    }

    .user-phone {
      font-size: 14px;
      color: #666;
    }
  }
}

/* 主内容区 */
.main-container {
  padding: 20px;
}

/* 顶部操作栏 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 10px;

  .operation-buttons {
    display: flex;
    gap: 10px;
  }
}

#header1 {
  height: 50px;
  border-bottom: 1px solid #ccc;
}

/* 对话框底部按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表格样式 */
.el-table {
  margin-bottom: 20px;
  box-sizing: border-box;
  padding-left: 100px;

  /* 表头样式 */
  th {
    background-color: #f5f7fa !important;
    font-weight: 700 !important;
    color: #333 !important;
  }

  .el-table__expand-icon {
    font-size: 16px;
    color: #999;
  }
}

/* 图标样式 */
:deep(.menu-icon) {
  font-size: 16px;
  color: #666;
}

.el-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;

  &.success {
    background-color: #f0f9eb;
    color: #67c23a;
  }

  &.danger {
    background-color: #fef0f0;
    color: #f56c6c;
  }
}

/* 操作按钮样式 */
.el-button[type="primary"] {
  background-color: #409eff;
  border-color: #409eff;

  &:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
  }
}

.page-header {
  flex-direction: row-reverse;
}

.el-form-item {
  display: flex;
  justify-content: space-between;
}
</style>